﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;

using System.Threading;

using CG.Security;
using CG.Security.Principal;



namespace td.Core.Security
{
    public partial class RightManagerForm : DevExpress.XtraEditors.XtraUserControl,IToolButton
    {
       public  List<Right> RightList = new List<Right>();
        DataTable roles, rights;
        Dictionary<int, string> roleDic;
        public  td.Core.Controls.tdGridView<Right> gridControl1 = new Controls.tdGridView<Right>();
        public RightManagerForm()
        {
            InitializeComponent();
            this.panelControl2.Controls.Add(gridControl1);
            gridControl1.Dock = DockStyle.Fill;
            InitGridView();
            BindData();

            roles = RoleManager.FindAll().Tables[0];
            roleDic = new Dictionary<int, string>();
            for (int i = 0; i < roles.Rows.Count; i++)
            {
                int id = int.Parse(roles.Rows[i]["role_id"].ToString());
                roleDic.Add(id, roles.Rows[i]["role_name"].ToString());
            }
            this.cbRoleName.Properties.Items.Add("");
            var e = roleDic.GetEnumerator();
            while (e.MoveNext())
            {
                this.cbRoleName.Properties.Items.Add(e.Current.Value);
            }
            this.gridControl1.gridView1.RowCellClick += new DevExpress.XtraGrid.Views.Grid.RowCellClickEventHandler(gridView1_RowCellClick);
        }

        void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left && e.Clicks > 1)
            {
                Right u = new Right();
                u.right_id = int.Parse(this.gridControl1.gridView1.GetRowCellDisplayText(e.RowHandle, "right_id"));
                u.right_name = this.gridControl1.gridView1.GetRowCellDisplayText(e.RowHandle, "right_name");
                u.right_description = this.gridControl1.gridView1.GetRowCellDisplayText(e.RowHandle, "right_description");
               
            }
        }

        /// <summary>
        /// 获取当前在列表中选中的用户
        /// </summary>
        /// <returns>userID</returns>
        public int  GetSelectedUser()
        {
            var rowindex = this.gridControl1.gridView1.FocusedRowHandle;
            return this.RightList[rowindex].right_id;
        }
        public void BindData()
        {           
            rights = CG.Security.RightManager .FindAll().Tables[0];
            RightList.Clear();
            for (int i = 0; i < rights.Rows.Count; i++)
            {
                RightList.Add(new Right()
                {
                    right_id = int.Parse(rights.Rows[i]["right_id"].ToString()),
                    right_name = rights.Rows[i]["right_name"].ToString(),
                    right_description = rights.Rows[i]["right_description"].ToString()                     
                });
            }
            this.gridControl1.DataSource = RightList.AsQueryable<Right>(); 
        }
        private void InitGridView()
        {
            this.gridControl1.DisplayColumns = "right_id,right_name,right_description";
            this.gridControl1.NonDisplayColumns = "right_id";
            this.gridControl1.AddColumnAlias("right_name", "权限名");
            this.gridControl1.AddColumnAlias("right_description", "权限描述");
            this.gridControl1.gridView1.OptionsBehavior.Editable = false;
        }

       
        /// <summary>
        /// 角色组合框变化 ，以角色查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbRoleName_SelectedIndexChanged(object sender, EventArgs e)
        {
            SerachUsers();
        }

        private void SerachUsers()
        {
            if (this.cbRoleName.Text != null && this.cbRoleName.Text != "")
            {
                var t = CG.Security.RoleManager.FindAll().Tables[0];
                int roleid = 0;
                for (int i = 0; i < t.Rows.Count; i++)
                {
                    if (t.Rows[i]["role_name"].ToString() == this.cbRoleName.Text.Trim())
                    {
                        roleid = (int)t.Rows[i]["role_id"];
                        break;
                    }
                }
                var roleright = CG.Security.RoleRightManager.FindByRole(roleid).Tables[0];
                Dictionary<int, int> rightInrole = new Dictionary<int, int>();
                for (int i = 0; i < roleright.Rows.Count; i++)
                {
                    rightInrole.Add((int)roleright.Rows[i]["right_id"], (int)roleright.Rows[i]["right_id"]);
                }
                var c = RightList.Where(p => rightInrole.Keys.Contains(p.right_id) && p.right_name.Contains(this.tbUserName.Text));
                this.gridControl1.DataSource = c.AsQueryable<Right>();
            }
            else
            {
                var c = RightList.Where(p => p.right_name.Contains(this.tbUserName.Text));
                this.gridControl1.DataSource = c.AsQueryable<Right>();
            }
        }

        private void tbUserName_TextChanged(object sender, EventArgs e)
        {
            SerachUsers();
        }


        public void OnNew()
        {
            AddRight addright = new AddRight();
            if (addright.ShowDialog() == DialogResult.OK)
            {
                CG.Security.RightManager.Create(addright.RightName, addright.RightDescription);
                this.BindData();
            }
        }

        public void OnSave()
        {
            
        }

        public void OnSaveAs()
        {
            
        }

        public void OnDelete()
        {
            
        }
    }
}

